﻿using Microsoft.EntityFrameworkCore;
using MyMes.Infrastructure;
using MyMES.Dto;
using MyMES.IServices.Equipments;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using VOL.Core.Extensions;
using VOL.Core.Utilities.Response;
using VOL.Entity.DomainModels.Core;
using VOL.Entity.DomainModels.Equipment;

namespace MyMES.Services.Equipments
{
    /// <summary>
    /// 设备维修单服务类，提供维修单相关的业务操作
    /// </summary>
    public class RepairFormService : IRepairFormService
    {
        private readonly IBaseRepository<RepairForm> _repairFormRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="repairFormRepository">维修单仓储接口</param>
        public RepairFormService(IBaseRepository<RepairForm> repairFormRepository)
        {
            _repairFormRepository = repairFormRepository;
        }

        /// <summary>
        /// 添加维修单
        /// </summary>
        /// <param name="repairForm">维修单实体</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> AddRepairForm(RepairForm repairForm)
        {
            WebResponseContent response = new WebResponseContent();
            try
            {

                // 检查维修单编号是否已存在
                bool exists = await _repairFormRepository.GetAll()
                    .AnyAsync(x => x.RepairCode == repairForm.RepairCode);

                if (exists)
                {
                    return response.Error("维修单编号已存在");
                }

                // 保存数据
                await _repairFormRepository.AddAsync(repairForm);
                return response.OK("添加维修单成功");
            }
            catch (Exception ex)
            {
                return response.Error($"添加维修单失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 删除维修单
        /// </summary>
        /// <param name="ids">维修单ID列表，以逗号分隔的字符串</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> DelRepairForm(string ids)
        {
            WebResponseContent response = new WebResponseContent();
            try
            {
                if (string.IsNullOrEmpty(ids))
                {
                    return response.Error("未选择要删除的记录");
                }

                // 将逗号分隔的字符串转换为整数ID列表
                List<int> idList = new List<int>();
                foreach (var id in ids.Split(','))
                {
                    if (int.TryParse(id, out int parsedId))
                    {
                        idList.Add(parsedId);
                    }
                }

                if (idList.Count == 0)
                {
                    return response.Error("无效的ID格式");
                }

                // 执行删除
                Expression<Func<RepairForm, bool>> expression = e => idList.Contains(e.Id);
                int result = await _repairFormRepository.DelAll(expression);

                if (result > 0)
                {
                    return response.OK($"成功删除{result}条记录");
                }
                else
                {
                    return response.Error("删除失败");
                }
            }
            catch (Exception ex)
            {
                return response.Error($"删除维修单失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 获取维修单列表
        /// </summary>
        /// <param name="dto">查询参数</param>
        /// <returns>分页数据</returns>
        public async Task<PageGridData<RepairForm>> GetRepairForm(GetRepairFormDto dto)
        {
            try
            {
                // 构建查询条件
                var query = _repairFormRepository.GetAll();

                // 应用筛选条件
                query = query.WhereIF(!string.IsNullOrEmpty(dto.RepairCode), x => x.RepairCode.Contains(dto.RepairCode));
                query = query.WhereIF(!string.IsNullOrEmpty(dto.RepairName), x => x.RepairName.Contains(dto.RepairName));
                query = query.WhereIF(!string.IsNullOrEmpty(dto.EquipmentCode), x => x.EquipmentCode.Contains(dto.EquipmentCode));
                query = query.WhereIF(!string.IsNullOrEmpty(dto.EquipmentName), x => x.EquipmentCode.Contains(dto.EquipmentName));
                query = query.WhereIF(!string.IsNullOrEmpty(dto.RepairResult), x => x.RepairResult.Contains(dto.RepairResult));
                query = query.WhereIF(dto.Status.HasValue, x => x.Status == dto.Status);

                // 计算总记录数
                int totalCount = await query.CountAsync();

                // 分页查询
                var pageIndex = dto.PageIndex <= 0 ? 1 : dto.PageIndex;
                var pageSize = dto.PageSize <= 0 ? 10 : dto.PageSize;
                var data = await query.OrderByDescending(x => x.Id)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize)
                    .ToListAsync();

                // 返回分页数据
                return new PageGridData<RepairForm>
                {
                    rows = data,
                    total = totalCount
                };
            }
            catch (Exception ex)
            {
                throw new Exception($"获取维修单列表失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 更新维修单
        /// </summary>
        /// <param name="repairForm">维修单实体</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> UpdRepairForm(RepairForm repairForm)
        {
            WebResponseContent response = new WebResponseContent();
            try
            {
                // 验证数据
                if (repairForm == null)
                {
                    return response.Error("更新数据不能为空");
                }
                
                if (string.IsNullOrEmpty(repairForm.RepairCode))
                {
                    return response.Error("维修单编号不能为空");
                }

                if (string.IsNullOrEmpty(repairForm.RepairName))
                {
                    return response.Error("维修单名称不能为空");
                }

                if (string.IsNullOrEmpty(repairForm.EquipmentCode))
                {
                    return response.Error("设备编码不能为空");
                }
                
                // 检查维修单是否存在
                var existingRepairForm = await _repairFormRepository.FindAsync(repairForm.Id);
                if (existingRepairForm == null)
                {
                    return response.Error("维修单不存在");
                }

                // 检查维修单编号是否已被其他记录使用
                bool exists = await _repairFormRepository.GetAll()
                    .AnyAsync(x => x.RepairCode == repairForm.RepairCode && x.Id != repairForm.Id);

                if (exists)
                {
                    return response.Error("维修单编号已被其他记录使用");
                }
                
                // 更新数据
                await _repairFormRepository.UpdateAsync(repairForm);
                return response.OK("更新维修单成功");
            }
            catch (Exception ex)
            {
                return response.Error($"更新维修单失败：{ex.Message}");
            }
        }
    }
}
